package bingo.component.dhtmlxgrid.config;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * Dec 17, 2008 11:04:32 AM
 * Author:snowbear11(chendw@bingosoft.net)
 * ReadMe:
 * ChangeLog:
 */
public class OptionConverter implements Converter {

	/* (non-Javadoc)
	 * @see com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object, com.thoughtworks.xstream.io.HierarchicalStreamWriter, com.thoughtworks.xstream.converters.MarshallingContext)
	 */
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		Option option = (Option)source;
		
		writeItem(writer, "id", option.getId());
		writeItem(writer, "value", option.getValue());
		writer.setValue(option.getTitle());
		
	}

	/* (non-Javadoc)
	 * @see com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, com.thoughtworks.xstream.converters.UnmarshallingContext)
	 */
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		Option option = new Option();
		
		if (StringUtils.isNotEmpty(reader.getAttribute("id"))) {
			option.setId(reader.getAttribute("id"));
		}		

		if (StringUtils.isNotEmpty(reader.getAttribute("value"))) {
			option.setValue(reader.getAttribute("value"));
		}
		
		if (StringUtils.isNotEmpty(reader.getValue())) {
			option.setTitle(reader.getValue());
		}		
		
		return option;
	}

	/* (non-Javadoc)
	 * @see com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	public boolean canConvert(Class type) {
		return type.equals(Option.class);
	}
	
	private void writeItem(HierarchicalStreamWriter writer, String name, String value) {
		if (StringUtils.isNotEmpty(value)) {
			writer.addAttribute(name, value);
		}
	}

}
